<%-- 
    Document   : uploadDoc
    Created on : 2016-4-1, 12:30:11
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script  type="text/javascript" src="${base}/js/jquery-1.9.1.js"></script>
        <script  type="text/javascript" src="${base}/js/angular/angular.min.js"></script>
        <script  type="text/javascript" src="${base}/js/jquery.cxhd.js"></script>
        <script  type="text/javascript" src="${base}/js/bootstrap.min.js"></script>
        <script  type="text/javascript" src="${base}/js/upload.js"></script>
        <link href='${base}/css/bootstrap-paper.css'  rel='stylesheet' type='text/css' />
        <link href='${base}/css/font-awesome.css'  rel='stylesheet' type='text/css' />
        <title class="pageTitle"></title>
    </head>
    <body ng-app="addDoc" ng-controller="mainCtrl">

        <div class="container">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <div style="float: left">
                        <button style="" onclick="$('#myfile').click()" class="btn btn-success btn-sm"><span class="fa fa-adn"></span>添加文档</button>
                        <button style="" ng-click="startCamera()" class="btn btn-success btn-sm"><span class="fa fa-adn"></span>拍照</button>

                        <input multiple="true" style="display: none" id="myfile" type="file" />
                    </div>
                    <div style="float: right">
                        <button ng-click="sendData()" class="btn btn-success btn-sm"><span class="fa fa-adn"></span>上传文档</button>
                    </div>
                    <div style="clear: both;"></div>
                </div>
                <div class="panel-body">
                    <div ng-repeat="image in files" class="col-xs-12 col-lg-4">
                        <input style="margin-bottom: 5px;" placeholder="事件名称" type="text" class="form-control" ng-model="image.event_description">
                        <select  class="form-control"  ng-model="image.docType">
                            <option value="其他文档">其他文档</option>
                            <option value="病历">病历</option>
                            <option value="医嘱">医嘱</option>
                            <option value="心电">心电</option>
                            <option value="检验">检验</option>
                        </select>
                        <a ng-click="addData(image, $event)" href="#" class="thumbnail">

                            <img ng-if="image.fileType == 'image'" ng-src="{{image.img}}" alt="">
                            <div ng-if="image.fileType == 'video'" style="width:100%;text-align: center;line-height: 300px;">
                                <i ng-hide="image.showVideo" ng-click="playVideo($index)" class="fa fa-vimeo-square" style="font-size: 48px;"></i>
                                <video  autoplay="true" width="320px" ng-show="image.showVideo" id="video{{$index}}" src="{{image.url}}"></video>
                            </div>
                        </a>
                    </div>
                    <div style="clear: both;"></div>
                </div>
            </div>
        </div>

        <canvas style="display: none;" width="1024px" height="768px" id="canvas1"></canvas>

        <div class="modal fade mode-x" role="dialog" aria-labelledby="gridSystemModalLabel">
            <div class="modal-dialog" role="document" style="width: 1100px">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="gridSystemModalLabel">拍照</h4>
                    </div>
                    <div class="modal-body">
                        <video id="video" autoplay="" width="1024px"></video>

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button  ng-click="scamera()" ng-disabled="users.$invalid" type="button" class="btn btn-primary"><span class="fa fa-save"></span>&nbsp;&nbsp;拍照</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
    </body>
</html>
<script>
    var info = Request.QueryString('data');
    info = decodeURIComponent(info);
    info = JSON.parse(info);
    $(".pageTitle").html("上传" + info.name + "的文档");
    angular.module("addDoc", [])

            .controller('mainCtrl', function ($scope) {

                $scope.files = [];
                $scope.images = [];
                $scope.uploadData = [];


                var gwidth = window.screen.width;
                var gheight = window.screen.height;
                //  alert(gwidth+"---"+gheight);
                var videoHeight = gheight / gwidth * 640;
                var llq = myBrowser();
                var cont = {
                    audio: false
                }
                if (llq == 'FF') {
                    cont.video = {width: {ideal: 640}, height: {ideal: videoHeight}};
                } else {
                    cont.video = {mandatory: {maxHeight: videoHeight, maxWidth: 640, minHeight: videoHeight, minWidth: 640}};
                }

                $scope.startCamera = function () {
                    $(".modal").modal('show');
                    // videoObj = {"video": true},
                    console.log(cont);
                    errBack = function (error) {
                        console.log("Video capture error: ", error.code);
                    };
                    //navigator.getUserMedia这个写法在Opera中好像是navigator.getUserMedianow       
                    if (navigator.getUserMedia) {
                        navigator.getUserMedia(cont, function (stream) {
                            video.src = stream;
                            video.play();
                        }, errBack);
                    } else if (navigator.webkitGetUserMedia) {
                        navigator.webkitGetUserMedia(cont, function (stream) {
                            video.src = window.webkitURL.createObjectURL(stream);
                            video.play();
                        }, errBack);

                    }
                }
                $scope.scamera = function () {
                    var videoElement = document.getElementById('video');
                    var canvasObj = document.getElementById('canvas1');
                    var context1 = canvasObj.getContext('2d');
                    //context1.fillStyle = "#ffffff";
                    //context1.fillRect(0, 0, 1024, 768);
                    // context1.translate(-1024 / 2, -768 / 2);  
                    // context1.rotate(Math.PI / 2);
                    //console.log(videoElement.offsetHeight+"===="+videoElement.width);
                    canvasObj.width = videoElement.offsetWidth;
                    canvasObj.height = videoElement.offsetHeight;
                    context1.drawImage(videoElement, 0, 0, videoElement.offsetWidth, videoElement.offsetHeight);

                    var base64 = canvasObj.toDataURL("image/png");
//                   // var base642 = canvasObj.toDataURL();
                    var file = convertBase64UrlToBlob(base64);
                    //var file={};
                    file.name = new Date().getTime() + ".png";
                    //console.log(base64);
                    file.img = base64;
                    file.fileType = "image";
                    file.docType = "文档";
                    $scope.files.push(file);
                    //$scope.$apply();
                    console.log($scope.files);

                    //console.log(canvasObj.toDataURL("image/png"));
                    //alert("PaiZhaoSuccess");
                }
                var param = {
                    fileInput: $("#myfile").get(0),
                    md5: false,
                    url: "uploadData",
                    filter: function (files) {

                        return files;
                    },
                    onSelect: function (files) {
                        for (var i = 0; i < files.length; i++) {
                            console.log(files[i]);
                            var file = files[i];
                            var imageType = /image.*/;
                            console.log(file.type.indexOf("image"));
                            console.log(file.type.indexOf("video"));
                            if (file.type.indexOf("image") > -1) {
                                file.fileType = "image";
                            } else if (file.type.indexOf("video") > -1) {
                                file.fileType = "video";
                            }
                             file.docType = "其他文档";
                            var fileSize = file.size / 1024;
                            fileSize = fileSize >= 1024 ? ((fileSize / 1024).toFixed(2) + "MB") : (fileSize.toFixed(0) + "KB");
                            file.fileSize = fileSize;

                            var reader = new FileReader();
                            reader.onload = function (e) {

                                console.log(file);
                                if (file.fileType == 'video') {
                                    file.url = URL.createObjectURL(file);
                                } else if (file.fileType == "image") {
                                    file.img = e.target.result;
                                }
                                $scope.files.push(file);
                                $scope.$apply();
                            };
                            // $scope.images.push(file);

                            reader.readAsDataURL(file);

                        }

                        //this.funUploadFile(files);

                    },
                    onProgress: function (file, uploadsize, totalsize, id) {

                        // $("#xl_progress").css("width", (uploadsize / totalsize).toFixed(2) * 100 + "%");

                        console.log(uploadsize + "  " + totalsize + "  " + (uploadsize / totalsize).toFixed(2) * 100 + "  " + id);

                    },
                    onSuccess: function (file, data) {
                        // console.log(file);
                        if(!file.docType){
                            file.docType ="其他文档";
                        }
                        $scope.uploadData.push({"event_name":file.docType, 'event_description': file.event_description, event_result: data, result_type: file.fileType, hospital_name: "云县人民医院"});

                    },
                    onComplete: function (patId) {
                        console.log($scope.uploadData);

                        $.cxhd.loading("提交数据中....");
                        $.post("saveLotInfo", {host_id: info.host_id, data: JSON.stringify($scope.uploadData)}, function (data) {
                            if (data == 'true') {
                                steveAl("上传成功", 1000);
                                window.opener.location.reload();
                                setTimeout(function () {
                                    console.log("刷新页面");
                                    location.reload();
                                }, 1000);
//                                $scope.uploadData = [];
//                                $scope.files = [];
//                                $scope.$apply();
                            } else {
                                steveAl("上传失败");
                            }
                        })

//                        $.post("saveOrder", $scope.data, function (data) {
//                            if (data == 'true') {
//                                steveAl("发送成功", 1000);
//                                $scope.data = {};
//                                $scope.fileIds = [];
//                                $scope.images = [];
//                                $scope.files = [];
//                                $scope.$apply();
//                            } else {
//                                steveAl("发送失败", 1000);
//                            }
//                        })
                    }
                }
                UploadFile = $.extend(UploadFile, param);
                UploadFile.init();

                $scope.playVideo = function (index) {
                    $scope.files[index].showVideo = true;
                    document.getElementById("video" + index).src = $scope.files[index].url;
                }
                /**
                 * 将以base64的图片url数据转换为Blob
                 * @param urlData
                 *            用url方式表示的base64图片数据
                 */
                var convertBase64UrlToBlob = function (urlData) {

                    var bytes = window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte

                    //处理异常,将ascii码小于0的转换为大于0
                    var ab = new ArrayBuffer(bytes.length);
                    var ia = new Uint8Array(ab);
                    for (var i = 0; i < bytes.length; i++) {
                        ia[i] = bytes.charCodeAt(i);
                    }

                    return new Blob([ab], {type: 'image/png'});
                }
                $scope.sendData = function () {
                    if ($scope.files.length > 0) {
                        $.cxhd.loading("");
                        UploadFile.funUploadFile($scope.files);
                    } else {
                        steveAl("请先选择文件");
                    }
//                    $http({method: "POST", url: "getOrderNo"}).success(function (data) {
//
//                        UploadFile.funUploadFile($scope.files);
//                    }).error(function () {
//                        steveAl("提交失败", 1000);
//                    });

                }

            });
    $(document).keydown(function (event) {
        console.log(event.keyCode);
    })


    function myBrowser() {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
        var isOpera = userAgent.indexOf("Opera") > -1;
        if (isOpera) {
            return "Opera"
        }
        ; //判断是否Opera浏览器
        if (userAgent.indexOf("Firefox") > -1) {
            return "FF";
        } //判断是否Firefox浏览器
        if (userAgent.indexOf("Chrome") > -1) {
            return "Chrome";
        }
        if (userAgent.indexOf("Safari") > -1) {
            return "Safari";
        } //判断是否Safari浏览器
        if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
            return "IE";
        }
        ; //判断是否IE浏览器
    }

</script>
